<!--
 * @Author: HuRrongChao 1556810922@qq.com
 * @Date: 2025-02-24 13:28:35
 * @LastEditors: HuRrongChao
 * @LastEditTime: 2025-04-18 21:13:34
-->

<template>
  <div class="chat-container">
    <!-- 左侧好友列表 -->
    <div class="chat-list">
      <div class="search-bar">
        <el-input
          v-model="searchText"
          placeholder="搜索用户"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
      
      <!-- 搜索结果展示 -->
      <div v-if="showSearchResults" class="search-results">
        <div class="search-header">
          <span>搜索结果</span>
          <el-button type="text" @click="closeSearch">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        
        <div class="result-list">
          <div v-for="user in searchResults" 
               :key="user.user_id" 
               class="result-item"
          >
            <el-avatar :src="user.avatar_url" />
            <div class="user-info">
              <div class="name">{{ user.author_name }}</div>
              <div class="description">{{ user.user_account }}</div>
            </div>
            <el-button 
              type="primary" 
              size="small"
              :class="{ 'is-followed': user.isrelationship }"
              @click="handleFollow(user)"
            >
              {{ user.isrelationship ? '已关注' : '关注' }}
            </el-button>
          </div>
        </div>
      </div>

      <div class="friend-list">
        <!-- 分组列表 -->
        <div v-for="group in groupedFriends" :key="group.type" class="friend-group">
          <div 
            class="group-header" 
            @click="toggleGroup(group.type)"
          >
            <el-icon class="collapse-icon" :class="{ 'is-collapsed': collapsedGroups[group.type] }">
              <CaretBottom />
            </el-icon>
            <span class="group-title">{{ group.title }} ({{ group.list.length }})</span>
          </div>
          
          <div v-show="!collapsedGroups[group.type]" class="group-content">
            <div 
              v-for="friend in group.list" 
              :key="friend.userId"
              class="friend-item"
              :class="{ active: currentChat?.userId === friend.userId }"
              @click="selectChat(friend)"
            >
              <el-avatar :src="friend.avatar" />
              <div class="friend-info">
                <div class="name">{{ friend.username }}</div>
                <div class="last-message" :title="friend.lastMessage">
                  {{ friend.lastMessage || '暂无消息' }}
                </div>
              </div>
              <span class="time">{{ friend.lastTime || '' }}</span>

              <!-- 添加悬浮按钮 -->
              <el-button
                class="action-btn"
                type="danger"
                size="small"
                :class="{ 
                  'unfollow-btn': group.type === 'following',
                  'remove-btn': ['followers', 'strangers'].includes(group.type),
                  'delete-btn': group.type === 'friends'
                }"
                @click.stop="handleAction(friend, group.type)"
              >
                {{ getActionButtonText(group.type) }}
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-main">
      <div class="chat-header">
        <span>{{ currentChat?.username || '聊天室' }}</span>
        <el-icon v-if="dropped" class="loading"><Loading /></el-icon>
      </div>

      <div class="chat-content" ref="chatContent">
        <template v-for="item in messages" :key="item.userId + item.time">
          <div class="message-item" :class="{ 'message-right': item.userId === user.user_id }">
            <div class="avatar">
              <el-avatar :src="item.avatar" />
              <div class="message-info">
                <span class="username">{{ item.username }}</span>
                <span class="time">{{ formatTime(item.time) }}</span>
              </div>
            </div>
            <div class="message-text" :class="{ 'self-message': item.userId === user.user_id }">
              {{ item.content }}
            </div>
          </div>
        </template>
      </div>

      <div class="chat-input">
        <div class="input-area">
          <el-input
            v-model="inputMessage"
            placeholder="say hello..."
            :disabled="dropped || !currentChat"
            @keyup.enter="sendMessage"
          >
            <template #prefix>
              <el-icon><ChatRound /></el-icon>
            </template>
            <template #suffix>
              <el-icon 
                class="send-icon" 
                @click="sendMessage" 
                :class="{ 
                  disabled: dropped || !currentChat,
                  'can-send': inputMessage.trim() && currentChat
                }"
              >
                <Position />
              </el-icon>
            </template>
          </el-input>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed, nextTick, onUnmounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { Search, Plus, Loading, Position, ChatRound, CaretBottom, Close } from '@element-plus/icons-vue'
import { formatTime } from '@/utils/common'
import { io } from 'socket.io-client'
import api from '@/api/axios.js'
import api_functions from '@/api/functions.js'
import { domain } from '@/config.js'

export default {
  name: 'FriendsChat',
  components: {
    Search,
    Plus,
    Loading,
    Position,
    ChatRound,
    CaretBottom,
    Close
  },
  setup() {
    const store = useStore()
    const chatContent = ref(null)
    const inputMessage = ref('')
    const messages = ref([])
    
    const user = computed(() => ({
      user_id: store.state.user.user_id,
      author_name: store.state.user.author_name,
      avatar: store.state.user.avatar_url || '/avatar.jpg'
    }))
    
    const socket = computed(() => store.state.chat?.socket)
    const dropped = computed(() => store.state.chat?.dropped || false)

    const searchText = ref('')
    const currentChat = ref(null)
    const friendList = ref([])
    const showSearchResults = ref(false)
    const searchResults = ref([])

    const collapsedGroups = ref({
      following: true,
      followers: true,
      friends: true,
      strangers: true
    })

    const toggleGroup = (type) => {
      collapsedGroups.value[type] = !collapsedGroups.value[type]
    }

    // 分组好友列表
    const groupedFriends = computed(() => {
      const groups = [
        { type: 'following', title: '关注', list: [] },
        { type: 'followers', title: '粉丝', list: [] },
        { type: 'friends', title: '好友', list: [] },
        { type: 'strangers', title: '陌生人', list: [] }
      ]

      friendList.value.forEach(friend => {
        switch (friend.type) {
          case 1:
            groups.find(g => g.type === 'following').list.push(friend)
            break
          case 2:
            groups.find(g => g.type === 'followers').list.push(friend)
            break
          case 3:
            groups.find(g => g.type === 'friends').list.push(friend)
            break
          default:
            groups.find(g => g.type === 'strangers').list.push(friend)
        }
      })

      return groups
    })

    // 初始化 socket 连接
    const initSocketConnection = () => {
      try {
        const socketInstance = io(domain, {
          transports: ['websocket'],
          query: {
            user_id: user.value.user_id,
            author_name: user.value.author_name
          }
        })

        // 连接成功
        socketInstance.on('connect', async() => {
          store.commit('chat/SET_DROPPED', false)
          const { data: {data} } = await api.getFriends()
          friendList.value = data.map(it => {
            return {
              ...it,
              lastTime: it.lastTime ? api_functions.getDateTransform(new Date(it.lastTime)) : ''
            }
          })
          ElMessage.success('聊天服务连接成功')
        })

        // 连接断开
        socketInstance.on('disconnect', () => {
          store.commit('chat/SET_DROPPED', true)
          ElMessage.warning('聊天服务已断开')
        })

        // 连接错误
        socketInstance.on('connect_error', () => {
          store.commit('chat/SET_DROPPED', true)
          ElMessage.error('聊天服务连接失败')
        })

        store.commit('chat/SET_SOCKET', socketInstance)
      } catch (error) {
        console.error('Socket connection error:', error)
        ElMessage.error('聊天服务初始化失败')
      }
    }

    // 初始化 socket 监听
    const initSocket = () => {
      if (socket.value) {
        // 监听新消息
        socket.value.on('newMessage', (message) => {
          // 如果当前正在和发送者聊天，则显示消息
          if (currentChat.value?.userId === message.userId) {
            messages.value.push({
              userId: message.userId,
              username: message.senderInfo.username,
              avatar: message.senderInfo.avatar,
              content: message.content,
              time: new Date(message.sendTime).getTime()
            })
            scrollToBottom()
          }
          console.log('msa', message)
        })

        // 监听消息发送成功
        socket.value.on('messageSent', (message) => {
          // 更新本地消息列表
          messages.value.push({
            userId: message.userId,
            username: message.senderInfo.username,
            avatar: message.senderInfo.avatar,
            content: message.content,
            time: new Date(message.sendTime).getTime()
          })
          scrollToBottom()
        })

        // 监听发送错误
        socket.value.on('messageError', (error) => {
          ElMessage.error(error.message || '发送消息失败')
        })
      }
    }

    // 发送消息
    const sendMessage = async () => {
      try {
        if (!currentChat.value || !inputMessage.value.trim() || !socket.value) {
          return
        }

        const message = {
          userId: user.value.user_id,
          receiverId: currentChat.value.userId,
          content: inputMessage.value,
          time: new Date().getTime()
        };

        // 通过 socket 发送实时消息
        socket.value.emit('friendMessage', {
          ...message,
          username: user.value.author_name,
          avatar: user.value.avatar
        })

        inputMessage.value = ''
        scrollToBottom()
      } catch (error) {
        ElMessage.error('发送消息失败')
      }
    }

    // 滚动到底部
    const scrollToBottom = () => {
      nextTick(() => {
        if (chatContent.value) {
          chatContent.value.scrollTop = chatContent.value.scrollHeight
        }
      })
    }

    const selectChat = async(friend) => {
      currentChat.value = friend
      try {
        const { data: { data } } = await api.getMessages({
          user_id: user.value.user_id,
          friend_id: friend.userId,
          page: 1,
          pageSize: 50
        })
        
        // 转换消息格式
        messages.value = data.map(msg => ({
          userId: msg.sender_id,
          username: msg.username,
          avatar: msg.avatar,
          content: msg.content,
          time: new Date(msg.send_time).getTime(),
          isRead: msg.is_read
        }))

        // 消息加载完成后滚动到底部
        nextTick(() => {
          scrollToBottom()
        })
      } catch (error) {
        console.error('获取消息失败:', error)
        ElMessage.error('获取消息记录失败')
      }
    }

    // 获取按钮文本
    const getActionButtonText = (type) => {
      switch (type) {
        case 'following':
          return '取关'
        case 'friends':
          return '删除'
        case 'followers':
        case 'strangers':
          return '移除'
        default:
          return ''
      }
    }

    // 处理按钮点击事件
    const handleAction = async (friend, type) => {
      try {
        await api.deleteFriendship({friend_id: friend.userId})
        ElMessage.success('操作成功')
        // 重新获取好友列表
        await initSocketConnection()
      } catch (error) {
        ElMessage.error('操作失败')
        console.error('Action failed:', error)
      }
    }

    // 处理搜索
    const handleSearch = async() => {
      if (!searchText.value.trim()) {
        ElMessage.warning('请输入搜索内容')
        return
      }
      showSearchResults.value = true
      // 这里可以调用实际的搜索API
      const { data: { data } } = await api.searchUsers({
        search: searchText.value
      })
      searchResults.value = data
    }

    // 关闭搜索结果
    const closeSearch = () => {
      showSearchResults.value = false
      searchText.value = ''
    }

    // 处理关注/取消关注
    const handleFollow = async (user) => {
      try {
        if (user.isrelationship) {
          await api.deleteFriendship({ friend_id: user.user_id })
          user.isrelationship = false
          ElMessage.success('取消关注成功')
        } else {
          await api.followUser({ friend_id: user.user_id })
          user.isrelationship = true
          ElMessage.success('关注成功')
        }
        await initSocketConnection()
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }

    onMounted(async () => {
      await nextTick(() => {
        setTimeout(() => {
          console.log(user.value.user_id)
          // 先初始化连接，再初始化监听
          initSocketConnection()
          initSocket()
        }, 100)
      })
    })

    // 组件销毁时断开连接
    onUnmounted(() => {
      if (socket.value) {
        socket.value.disconnect()
        store.commit('chat/SET_SOCKET', null)
      }
    })

    return {
      user,
      socket,
      dropped,
      chatContent,
      inputMessage,
      messages,
      sendMessage,
      scrollToBottom,
      formatTime,
      searchText,
      currentChat,
      friendList,
      selectChat,
      collapsedGroups,
      toggleGroup,
      groupedFriends,
      getActionButtonText,
      handleAction,
      showSearchResults,
      searchResults,
      handleSearch,
      closeSearch,
      handleFollow
    }
  }
}
</script>

<style lang="scss" scoped>
.chat-container {
  height: 100%;
  display: flex;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 8px;
  overflow: hidden;

  .chat-list {
    width: 250px;
    background: rgba(0, 0, 0, 0.3);
    border-right: 1px solid rgba(255, 255, 255, 0.1);
    display: flex;
    flex-direction: column;

    .search-bar {
      padding: 10px;
      background: rgba(0, 0, 0, 0.2);

      :deep(.el-input) {
        --el-input-bg-color: rgba(0, 0, 0, 0.3);
        --el-input-border-color: transparent;
        --el-input-text-color: #fff;
        --el-input-placeholder-color: rgba(255, 255, 255, 0.5);

        .el-input__wrapper {
          box-shadow: none;
        }

        .el-input-group__append {
          background: transparent;
          border: none;
          padding: 0 5px;
        }
      }
    }

    .friend-list {
      flex: 1;
      overflow-y: auto;

      .friend-group {
        .group-header {
          padding: 10px 15px;
          display: flex;
          align-items: center;
          cursor: pointer;
          color: rgba(255, 255, 255, 0.8);
          transition: all 0.3s;

          &:hover {
            background: rgba(255, 255, 255, 0.1);
          }

          .collapse-icon {
            margin-right: 8px;
            transition: transform 0.3s;
            font-size: 16px;
            
            &.is-collapsed {
              transform: rotate(-90deg);
            }
          }

          .group-title {
            font-size: 14px;
            font-weight: 500;
          }
        }

        .group-content {
          .friend-item {
            position: relative;
            padding: 12px 15px 12px 35px;
            display: flex;
            align-items: center;
            cursor: pointer;
            transition: all 0.3s;

            &:hover {
              background: rgba(255, 255, 255, 0.1);
            }

            &.active {
              background: rgba(255, 255, 255, 0.15);
            }

            .action-btn {
              position: absolute;
              right: 10px;
              top: 50%;
              transform: translateY(-50%);
              opacity: 0;
              transition: opacity 0.3s;
              z-index: 112;
              
              &.unfollow-btn {
                --el-button-hover-bg-color: #f56c6c;
                --el-button-hover-border-color: #f56c6c;
              }
              
              &.delete-btn {
                --el-button-hover-bg-color: #e6a23c;
                --el-button-hover-border-color: #e6a23c;
              }
              
              &.remove-btn {
                --el-button-hover-bg-color: #909399;
                --el-button-hover-border-color: #909399;
              }
            }

            &:hover .action-btn {
              opacity: 1;
            }

            .el-avatar {
              flex-shrink: 0;
            }

            .friend-info {
              flex: 1;
              margin-left: 12px;
              min-width: 0;

              .name {
                font-size: 14px;
                color: #fff;
                margin-bottom: 4px;
                font-weight: 500;
              }

              .last-message {
                font-size: 12px;
                color: rgba(255, 255, 255, 0.6);
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
              }
            }

            .time {
              font-size: 12px;
              color: rgba(255, 255, 255, 0.4);
              margin-left: 8px;
            }
          }
        }
      }
    }
  }

  .chat-main {
    flex: 1;
    display: flex;
    flex-direction: column;

    .chat-header {
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(0, 0, 0, 0.2);
      color: #fff;
      font-size: 16px;
      position: relative;

      .loading {
        margin-left: 10px;
        font-size: 18px;
      }
    }

    .chat-content {
      flex: 1;
      padding: 20px;
      overflow-y: auto;
      background: rgba(0, 0, 0, 0.1);

      .message-item {
        margin-bottom: 20px;
        text-align: left;

        .avatar {
          display: flex;
          align-items: center;
          margin-bottom: 5px;

          .message-info {
            margin-left: 10px;
            
            .username {
              color: rgba(255, 255, 255, 0.8);
              font-size: 14px;
            }

            .time {
              color: rgba(255, 255, 255, 0.3);
              font-size: 12px;
              margin-left: 10px;
            }
          }
        }

        .message-text {
          margin-left: 40px;
          padding: 10px 15px;
          background: rgba(255, 255, 255, 0.1);
          border-radius: 4px;
          color: #fff;
          display: inline-block;
          max-width: 60%;
          word-break: break-word;
        }

        &.message-right {
          text-align: right;

          .avatar {
            flex-direction: row-reverse;
            
            .message-info {
              margin-right: 10px;
              margin-left: 0;
              text-align: right;
            }
          }

          .message-text {
            margin-right: 40px;
            margin-left: 0;
            background: var(--el-color-primary);
            &.self-message {
              background: var(--el-color-primary);
            }
          }
        }
      }
    }

    .chat-input {
      padding: 20px;
      background: rgba(0, 0, 0, 0.2);

      .input-area {
        :deep(.el-input) {
          --el-input-bg-color: rgba(0, 0, 0, 0.3);
          --el-input-border-color: transparent;
          --el-input-text-color: #fff;
          --el-input-placeholder-color: rgba(255, 255, 255, 0.5);

          .el-input__wrapper {
            box-shadow: none;
            padding: 8px 15px;
          }

          .el-input__prefix,
          .el-input__suffix {
            color: rgba(255, 255, 255, 0.5);
          }

          .send-icon {
            cursor: pointer;
            transition: all 0.3s;
            color: rgba(255, 255, 255, 0.5);

            &.can-send {
              color: var(--el-color-primary);
            }

            &:hover:not(.disabled) {
              transform: scale(1.1);
            }

            &.disabled {
              cursor: not-allowed;
              opacity: 0.5;
            }
          }
        }
      }
    }
  }

  // 自定义滚动条样式
  .chat-content, .friend-list {
    &::-webkit-scrollbar {
      width: 6px;
      height: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background: rgba(255, 255, 255, 0.2);
      border-radius: 3px;
      cursor: pointer;

      &:hover {
        background: rgba(255, 255, 255, 0.3);
      }
    }

    &::-webkit-scrollbar-track {
      background: transparent;
    }

    // Firefox 滚动条样式
    scrollbar-width: thin;
    scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
  }

  .chat-content {
    &:hover {
      &::-webkit-scrollbar-thumb {
        background: rgba(255, 255, 255, 0.3);
      }
    }
  }

  .friend-list {
    &:hover {
      &::-webkit-scrollbar-thumb {
        background: rgba(255, 255, 255, 0.3);
      }
    }
  }

  .search-results {
    width: 250px;
    position: absolute;
    top: 52px;
    left: 0;
    right: 0;
    background: #272a37;
    z-index: 10;

    .search-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 10px 10px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      color: #fff;
    }

    .result-list {
      min-height: 300px;
      max-height: 500px;
      overflow-y: auto;
    }

    .result-item {
      display: flex;
      align-items: center;
      padding: 10px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      transition: background-color 0.3s;

      &:hover {
        background: rgba(255, 255, 255, 0.1);
      }

      .el-avatar--circle {
        flex-shrink: 0;
      }

      .user-info {
        width: 120px;
        margin-left: 12px;
        color: #fff;

        .name {
          font-size: 14px;
          font-weight: 500;
        }

        .description {
          font-size: 12px;
          color: rgba(255, 255, 255, 0.6);
          margin-top: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .el-button {
        &.is-followed {
          background-color: transparent;
          border-color: rgba(255, 255, 255, 0.3);
          color: rgba(255, 255, 255, 0.6);

          &:hover {
            background-color: #f56c6c;
            border-color: #f56c6c;
            color: #fff;
          }
        }
      }
    }
  }

  .result-list {
    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background: rgba(255, 255, 255, 0.2);
      border-radius: 3px;
    }

    &::-webkit-scrollbar-track {
      background: transparent;
    }
  }
}

.el-button--text {
  color: #fff !important;
}

// 暗黑模式下的滚动条样式
html.dark {
  .chat-container {
    .chat-content, .friend-list {
      &::-webkit-scrollbar-thumb {
        background: rgba(255, 255, 255, 0.1);

        &:hover {
          background: rgba(255, 255, 255, 0.2);
        }
      }
    }
  }
}
</style>
